package vn.com.bookstore.util.coverflow;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;

@SuppressWarnings("deprecation")
public class CustomGallery extends Gallery{
	private int centerOfGallery;
	private Camera mCamera = new Camera();
	private float maxScale = 1.0f;

	public CustomGallery(Context context) {
	    super(context);
	    init();
	}

	public CustomGallery(Context context, AttributeSet attrs) {
	    super(context, attrs);
	    init();
	}

	public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
	    super(context, attrs, defStyle);
	    init();
	}

	private void init() {
	    setStaticTransformationsEnabled(true);
	}

	private int getCenterWidthOfView(View child) {
	    return child.getLeft() + child.getWidth() / 2;
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
	    super.onSizeChanged(w, h, oldw, oldh);
	    centerOfGallery = (w - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
	}

	@Override
	protected boolean getChildStaticTransformation(View child, Transformation t) {
	    mCamera.save();
	    final Matrix matrix = t.getMatrix();
	    final int centerWidthOfChild = getCenterWidthOfView(child);
	    final int delta = centerOfGallery - centerWidthOfChild;

	    final float scale = (float)(maxScale - Math.abs(delta) * 0.1f / centerOfGallery);
	    mCamera.getMatrix(matrix);
	    matrix.preScale(scale, scale);
	    matrix.preTranslate(10, 10);
	    matrix.postTranslate(-10, -10);
	    mCamera.restore();

	    if (android.os.Build.VERSION.SDK_INT >= 15) { // For Jelly Bean hack
	        child.invalidate();
	    }

	    return true;
	}
}
